<template>
    <el-main class="pt-2 pb-0">
        <div class="overflow-y-auto" :style="{ height: cHeight + 'px' }" v-loading="loading">
            <el-row :gutter="20" style="width: 98%;">
                <el-col :span="6" v-for="(item, index) in images" :key="index">
                    <el-card shadow="hover" class="relative mt-3">
                        <el-image :src="toAbsoluteUrl(item.url)" fit="cover" class="w-full h-[160px]" :preview-src-list="previewList"
                            :initial-index="index" />
                        <div class="absolute text-sm"
                            style="left: 0; right: 0; bottom: 20px; height: 20px; color: white; background-color: rgb(0 0 0/0.2); white-space: nowrap;">
                            {{ item.id + '|' + item.name }}</div>
                        <template #footer>
                            <div class="text-sm flex items-center justify-center">
                                <el-radio v-if="selectable && !multi" :value="item.id" v-model="currentId" class="h-[20px] w-[10px]" @change="onChange"/>
                                <el-checkbox v-if="selectable && multi && !(selectedUrls.includes(item.url))" :value="item.id"
                                class="h-[20px] w-[10px]" @change="toggleSelection(item.id)"/>
                                <span v-if="selectable && multi && (selectedUrls.includes(item.url))" class="text-xs">已选择</span>
                                <el-button type="primary" link @click="onRenameImg(item.id)" class="ml-2">重命名</el-button>
                                <el-popconfirm title="确定删除该图片吗？" @confirm = "onRemoveImg(item.id)">
                                    <template #reference>
                                        <el-button type="primary" link >删除</el-button>
                                    </template>
                                </el-popconfirm>
                            </div>
                        </template>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <div style="height: 50px;" class="flex items-center justify-center">
            <el-pagination layout="prev, pager, next" background :current-page="currentPage" :total="total"
                :page-size="limit" @current-change="onPageChange" />
        </div>
    </el-main>

    <el-drawer v-model="showUpload" title="上传图片" :close-on-click-modal="false" :destroy-on-close="true" @close="onCloseImageUpload">
        <div class="mydrawer-container">
            <div class="body" v-loading="loading" element-loading-text="Loading...">
                <slot>
                    <UploadFile :imageClassId="imageClassId" @upload-change = "onUploadChange"/>
                </slot>
            </div>
        </div>
    </el-drawer>
</template>
<script setup>
import { ref, onMounted, watch } from 'vue'
import { getImagesByCatogeryId, renameImage, deleteImage } from '../api/image'
import { toast, showPrompt, toAbsoluteUrl } from "../composables/util"
import UploadFile from './UploadFile.vue';
// 本组件对外暴露的属性
const props = defineProps({
    cHeight: Number,
    categoryId: Number,
    selectable:{
        type: Boolean,
        default: false
    },
    multi: {
        type: Boolean,
        default: false
    },
    selectedUrls: {
        type: Array,
        default: []
    }
})

const imageClassId = ref(0)
// 监听current 如果current发生变化，则出发change事件
watch(() => props.categoryId, () => { 
    imageClassId.value = props.categoryId
    getData() })

const currentId = ref(0) // 当前被选中的图片ID
const onChange = (id) => {
    currentId.value = id
}

const ids = ref([])
const toggleSelection = (id) => {
  if (ids.value.includes(id)) {
    // 如果已选中，则移除
    ids.value = ids.value.filter(selectedId => selectedId !== id)
  } else {
    // 如果未选中，则添加
    ids.value.push(id)
  }
}

// 获取图片分类数据
const images = ref(null)
const total = ref(0) // 分类总记录数
const limit = ref(12) // 每页显示的条数
const currentPage = ref(1) // 当前页码
const previewList = ref(null) // 预览图片集合
const loading = ref(false) // 图片列表区域loading控制
onMounted(() => {
    currentPage.value = 1
    getData()
})

const onPageChange = (newPaegIndex) => {
    currentPage.value = newPaegIndex
    getData()
}

const getData = () => {
    if (props.categoryId > 0) {
        loading.value = true
        getImagesByCatogeryId(props.categoryId, currentPage.value, limit.value).then(res => {
            images.value = res.data.list
            previewList.value = []
            images.value.forEach(item => {
                previewList.value.push(toAbsoluteUrl(item.url))
            })
            total.value = res.data.totalCount
        }).finally(() => {
            loading.value = false
        })
    }
}

// 重命名图片
const onRenameImg = (id) => {
    const img = images.value.find(item => item.id == id)
    if (img) {
        showPrompt('请输入该图片的新名称', '图片重命名', img.name).then(({ value }) => {
            renameImage(id, value).then(res => {
                toast('重命名名称成功！')
                getData()
            })
        })
    }

}

// 删除对应图片
const onRemoveImg = (id) => {
    deleteImage([id]).then(res=>{
        toast('删除图片成功！')
        getData()
    })
}

// 上传图片
const showUpload = ref(false)
const openUploadFile = () => {
    showUpload.value = true
}

const uploadFiles = ref(null)
const onUploadChange = (e) => {
    uploadFiles.value = e
}

const onCloseImageUpload = () => {
    if(uploadFiles.value && uploadFiles.value.length > 0){
        currentPage.value = 1
        getData()
    }
}

const getSelectedImageUrl = () => {
    // 单选时
    if(!props.multi && currentId.value > 0) {
        let img = images.value.find(item => item.id == currentId.value)
        if(img) return img.url
    }
    // 多选时
    if(props.multi && ids.value.length > 0) {
        let arr = []
        ids.value.forEach(i=>{
            let img = images.value.find(item => item.id == i)
            if(img) return arr.push(img.url)
        })
        return arr
    } 
    return props.multi ? [] : '' 
}

const setSelectedImageUrls = (urls) => {
    if (Array.isArray(urls)) {
        
    }
}

defineExpose({openUploadFile, getSelectedImageUrl, setSelectedImageUrls})



</script>
<style scoped>
:deep(.el-card__footer) {
    padding: 0;
}

:deep(.el-card__body) {
    padding: 0;
    margin-bottom: -7px;
}
</style>